<?php
chdir('../');

require('includes/setUp.php');
/*
var_dump($_POST);die;
*/

if ($user == null )
  globalFunc::redirect(WebRoot.'index.php?errMsg='.rawurlencode(T_('You have to be logged on!')));


$album = new Album();
if(isset($_POST['album']['idAlbum'])) {
  $album = $db->find('Album', $_POST['album']['idAlbum']);
  if ($album->User != $user)
    globalFunc::redirect(WebRoot.'index.php?errMsg='.rawurlencode(T_('You aren\'t owner of this album!')));
}

try {
  $album->Name          = (empty($_POST['album']['name'])) ? null : $_POST['album']['name'];
  $album->Description   = (empty($_POST['album']['description'])) ? null : $_POST['album']['description'];
  $album->User          = $user;
  $album->AllowComments = (isset($_POST['album']['comments'])) ? true : false;
  $album->ParentAlbum   = $db->find('Album', $_POST['album']['parent']);
  $album->Protection    = $db->find('Protection', $_POST['album']['protection']);

  if($_POST['album']['protection'] == 'password') {
    $album->Password     = (empty($_POST['album']['password'])) ? null : globalFunc::hashPassword($_POST['album']['password']);
  }

  foreach ($album->AllowedUsers as $user) {
    $album->removeAllowedUser($user);
  }

  if($_POST['album']['protection'] == 'private' && isset($_POST['allowedUsers'])) {
    foreach($_POST['allowedUsers'] as $value) {
      $album->addAllowedUser($db->getRepository('User')->findOneByUserName($value));
    }
  }

  if(!isset($_POST['album']['idAlbum'])) $db->persist($album);
  $db->flush();
} catch (Exception $ex){
  
  $paramStr = '';
  if (isset($_POST['album']['idAlbum'])) $paramStr = 'idAlbum='.$_POST['album']['idAlbum'].'&';
  if (isset($_POST['album']['parentAlbum'])) $paramStr = 'parentAlbum='.$_POST['album']['parent'].'&';
  globalFunc::redirect(WebRoot.'editAlbum.php?'.$paramStr.'errMsg='.rawurlencode($ex->getMessage()));
  exit;
  
}

globalFunc::redirect(WebRoot.'album.php?idAlbum='.$album->idAlbum);